﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Convertor.Interface;

namespace Convertor
{
    public enum UpdateIntervalTypes
    {
        EveryTime = 0,
        OneDay = 1,
        SevenDays = 7,
        FifteenDays = 15,
        ThirtyDays = 30
    }
    class UpdateEventArg : EventArgs
    {
        public UpdateEventArg()
        {
        }
        public UpdateEventArg(bool hasUpdate)
        {
            this.HasUpdate = hasUpdate;
        }
        public bool HasUpdate { get; set; }
    }

    delegate void UpdateEventHanler(object sender, UpdateEventArg e);
    class UpdateHandler
    {
        private static IConvertParamters content = new ConvertParamters(Config.DOWNLOAD_URL, Config.DOWNLOAD_URL);
        private static string path = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, @"HiddenTemplate\Update.cvt1");

        private TemplateToSaveContainer template;
        private IConvertHelper converter;

        public event UpdateEventHanler HasUpdateEnvent;

        public UpdateHandler()
        {
            this.converter = new ConvertHelper();
            template = PluginHandler.LoaTemplateFromSerializeFile(path);
        }

        public void CheckUpdate()
        {
            startCheck();
        }

        public void StartCheckUpdate()
        {
            Thread th = new Thread(new ThreadStart(startCheck));
            th.IsBackground = true;
            th.Start();
        }

        private void startCheck()
        {
            Config.GlobalConfig.LastCheckedUpdate = DateTime.Now;

            var b = converter.OutputFunc(content, template.Plugins);
            try
            {
                Version online = new Version(b.OutputContent.ToString().Trim());
                Version offline = new Version(Config.HelpContent.Version);
                Config.GlobalConfig.HasUpdate = online > offline;
            }
            catch { }

            if (HasUpdateEnvent != null)
            {
                HasUpdateEnvent(this, new UpdateEventArg(Config.GlobalConfig.HasUpdate));
            }
        }
    }
}
